//
//  ApplyIndividualViewController.m
//  YongChuanTradingArea
//
//  Created by Vivian on 2017/9/28.
//  Copyright © 2017年 李冰. All rights reserved.
//

#import "ApplyIndividualViewController.h"
#import "ApplySelectAreaController.h" // 选择省市区
#import "DirectionButton.h"

@interface ApplyIndividualViewController ()<CLLocationManagerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (weak, nonatomic) IBOutlet UILabel *cityLabel;
@property (weak, nonatomic) IBOutlet UITextField *nameTF;
@property (weak, nonatomic) IBOutlet UITextField *telTF;
@property (weak, nonatomic) IBOutlet DirectionButton *firstBtn;
@property (weak, nonatomic) IBOutlet DirectionButton *secondBtn;
@property (weak, nonatomic) IBOutlet UIImageView *firstImage;
@property (weak, nonatomic) IBOutlet UIImageView *secondImage;
@property (nonatomic, strong) NSString *firstImageId;
@property (nonatomic, strong) NSString *secondImageId;
@property (weak, nonatomic) DirectionButton *currentBtn;
@property (weak, nonatomic) IBOutlet UITextField *contactTF;
@property (weak, nonatomic) IBOutlet UITextField *bankBeginTF;
@property (weak, nonatomic) IBOutlet UITextField *bankNameTF;
@property (weak, nonatomic) IBOutlet UITextField *bankAccTF;
@property (weak, nonatomic) IBOutlet UIButton *agreeBtn;

@property (nonatomic, strong) NSString *proviceId;
@property (nonatomic, strong) NSString *cityId;
@property (nonatomic, strong) NSString *countyId;

// 位置服务
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) NSString *locationAddressName;
@property (nonatomic, strong) CLLocation *location;

@end

@implementation ApplyIndividualViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"注册个人合伙人";
    self.firstBtn.spaceBetweenTitleAndImage = 10;
    self.secondBtn.spaceBetweenTitleAndImage = 10;
    [self.agreeBtn setAttributedTitle:[self.agreeBtn.titleLabel.text changeColor:kMainColor range:NSMakeRange(self.agreeBtn.titleLabel.text.length - 6, 6)] forState:UIControlStateNormal];
    self.view.backgroundColor = kBgColor;
    
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.distanceFilter = 1000;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers;
    
    if (_isAgain)
    {
        
        [LBNetworkingInstance requestGET:getMenberInfo parameters:@{@"id":[LBUserManage defaultManager].user_id} showHUD:YES success:^(id  _Nonnull responseObject, NSInteger code, NSString * _Nonnull message) {
            
            if (code == YCNetworkingStatusCodeSuccess)
            {
                UserModel *userModel = [UserModel yy_modelWithJSON:responseObject[@"Data"]];
                [LBUserManage defaultManager].userModel = userModel;
                
                self.nameTF.text = userModel.USERNAME;
                self.telTF.text = userModel.MOBILE;
                self.contactTF.text = userModel.CONTACTPHONE;
                self.bankBeginTF.text = userModel.BANKUSER;
                self.bankNameTF.text = userModel.BANKNAME;
                self.bankAccTF.text = userModel.BANKNUMBER;
                self.proviceId = userModel.PROVIINCEID;
                self.cityId = userModel.CITYID;
                self.countyId = userModel.COUNTYID;
                NSString *address = [NSString stringWithFormat:@"%@%@%@", userModel.PROVIINCENAME, userModel.CITYNAME, userModel.COUNTYNAME];
                _cityLabel.text = address.length == 0 ? @"地区" : address;
                
                for (UserModelImgList *list in userModel.ImgList) {
                    if ([list.imgtype isEqualToString:@"GRHHRSFZ"]) {
                        [_firstImage sd_setImageWithURL:[NSURL URLWithString:list.image]];
                    }
                    if ([list.imgtype isEqualToString:@"GRHHRSCSFZ"]) {
                        [_secondImage sd_setImageWithURL:[NSURL URLWithString:list.image]];
                    }
                }
            }
        }];
        
    }
}

- (void)resignAllTF{
    [self.nameTF resignFirstResponder];
    [self.telTF resignFirstResponder];
    [self.contactTF resignFirstResponder];
    [self.bankBeginTF resignFirstResponder];
    [self.bankNameTF resignFirstResponder];
    [self.bankAccTF resignFirstResponder];
    
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    
    
    if (status == kCLAuthorizationStatusAuthorizedAlways || status == kCLAuthorizationStatusAuthorizedWhenInUse)
    {
        //        [self.locationManager startUpdatingLocation];
        [self.locationManager startUpdatingLocation];
    }
    else if(status == kCLAuthorizationStatusDenied)
    {
        [self _alertUserSetting];
    }
    else if (status == kCLAuthorizationStatusNotDetermined)
    {
        [self.locationManager requestWhenInUseAuthorization];
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    
    CLLocation *currentLocation = locations.lastObject;
    //    [LBUserManage defaultManager].location = currentLocation;
    self.location = currentLocation;
    
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *array, NSError *error)
     {
         if (array.count > 0)
         {
             CLPlacemark *place = [array objectAtIndex:0];
             //获取城市
             NSString *city = place.locality;
             if (!city)
             {
                 city = place.administrativeArea;
             }
             NSLog(@"location city %@  ",city);
             self.locationAddressName = [NSString stringWithFormat:@"%@%@%@%@%@", place.administrativeArea ?: @"", place.subAdministrativeArea ?: @"", city, place.thoroughfare ?: @"", place.subThoroughfare ?: @""];
         }
     }];
}

- (void) _alertUserSetting {
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示"  message:@"未授权定位服务，是否现在设置？" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        [alertVC dismissViewControllerAnimated:YES completion:nil];
    }];
    
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //        NSLog(@"%@", [NSURL URLWithString:UIApplicationOpenSettingsURLString]);
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    }];
    
    [alertVC addAction:cancelAction];
    [alertVC addAction:sureAction];
    
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertVC animated:YES completion:nil];
}

- (IBAction)cityBtnAction:(UIButton *)sender {
    [self resignAllTF];
    ApplySelectAreaController *vc = [ApplySelectAreaController new];
    WEAKSELF;
    vc.selectBlock = ^(NSString *provinceId, NSString *cityId, NSString *areaId, NSString *address) {
        
        weakSelf.proviceId = provinceId;
        weakSelf.cityId = cityId;
        weakSelf.countyId = areaId;
        weakSelf.cityLabel.text = address.length == 0 ? @"地区" : address;
    };
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)certifBtnAction:(DirectionButton *)sender {
    [self resignAllTF];
    _currentBtn = sender;
    [self editBtnClicked];
}

- (IBAction)agreeBtnAction:(UIButton *)sender {
    [self resignAllTF];
    sender.selected = !sender.selected;
}

- (IBAction)submitBtnAction:(UIButton *)sender {
    [self resignAllTF];
    if (!_agreeBtn.selected)
    {
        [MBProgressHUD showMessageWithOutIcon:@"请阅读同意协议"];
        return;
    }
    UserModel *userModel = [LBUserManage defaultManager].userModel;
    for (UserModelImgList *list in userModel.ImgList) {
        if ([list.imgtype isEqualToString:@"GRHHRSFZ"]) {
            _firstImageId = list.ID;
        }
        if ([list.imgtype isEqualToString:@"GRHHRSCSFZ"]) {
            _secondImageId = list.ID;
        }
    }
    
    NSString *cId = userModel.ID;
    NSString *mType = @"4";// 类型2：会员店，3：企业合伙人，4：个人合伙人
    NSString *cName = self.nameTF.text;
    NSString *cCellPhone = self.telTF.text;
    NSString *contactPhone = self.contactTF.text;
    NSString *bankUserName = self.bankBeginTF.text;
    NSString *bankName = self.bankNameTF.text;
    NSString *bankNumber = self.bankAccTF.text;
    NSString *proviceId = self.proviceId;
    NSString *cityId = self.cityId;
    NSString *countyId = self.countyId;
    NSString *imgIds = [NSString stringWithFormat:@"%@,%@,", _firstImageId, _secondImageId];
    NSString *address = self.locationAddressName;
    NSString *xPoint = [NSString stringWithFormat:@"%f", self.location.coordinate.longitude];
    NSString *yPoint = [NSString stringWithFormat:@"%f", self.location.coordinate.latitude];
    
    if (!_firstImageId || !_secondImageId)
    {
        [MBProgressHUD showMessageWithOutIcon:@"请上传图片"];
        return;
    }
    
    if (mType.length == 0 || cCellPhone.length == 0 || cName.length == 0 || contactPhone.length == 0 || contactPhone.length == 0 ||
        bankName.length == 0 || bankUserName.length == 0 || bankNumber.length == 0 ||
        proviceId.length == 0)
    {
        
        [MBProgressHUD showMessageWithOutIcon:@"请输入完整信息"];
        return;
    }
    
    NSDictionary *params = NSDictionaryOfVariableBindings(cId, mType,cCellPhone,cName,contactPhone,bankName,bankUserName,bankNumber,proviceId,imgIds);
    
    NSMutableDictionary *mutableParams = params.mutableCopy;
    
    if (cityId)
    {
        [mutableParams setObject:cityId forKey:@"cityId"];
    }
    if (countyId)
    {
        [mutableParams setObject:countyId forKey:@"countyId"];
    }
    
    if (address)
    {
        [mutableParams setObject:address forKey:@"address"];
    }
    if (xPoint)
    {
        [mutableParams setObject:xPoint forKey:@"xPoint"];
    }
    if (yPoint)
    {
        [mutableParams setObject:yPoint forKey:@"yPoint"];
    }
    [LBNetworkingInstance requestGET:upgradeStore parameters:mutableParams.copy showHUD:YES success:^(id  _Nonnull responseObject, NSInteger code, NSString * _Nonnull message) {
        
        if (code == YCNetworkingStatusCodeSuccess)
        {
            [MBProgressHUD showMessageWithOutIcon:@"申请成功"];
            [UIViewController toHome];
        }
        else
        {
            [MBProgressHUD showMessageWithOutIcon:responseObject[@"ResultMsg"]];
        }
    }];
    
}

- (void)editBtnClicked{
    __weak typeof(self) weakSelf = self;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"选择相片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *album = [UIAlertAction actionWithTitle:@"相册🌌" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        // 去更新图片
        [weakSelf chosePhoto:ChosePhotoTypeAlbum];
    }];
    
    UIAlertAction *camera = [UIAlertAction actionWithTitle:@"相机📷" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        // 去更新图片
        [weakSelf chosePhoto:ChosePhotoTypeCamera];
    }];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        
    }];
    [alert addAction:album];
    [alert addAction:camera];
    [alert addAction:cancel];
    
    [self presentViewController:alert animated:YES completion:^{
        
    }];
}

#pragma mark - 选择照片
- (void)chosePhoto:(ChosePhotoType)type
{
    UIImagePickerController *piker = [[UIImagePickerController alloc] init];
    piker.delegate = self;
    // 设置编辑模式
    piker.allowsEditing = YES;
    
    if (type == ChosePhotoTypeAlbum) {
        piker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }else if (type == ChosePhotoTypeCamera) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            piker.sourceType = UIImagePickerControllerSourceTypeCamera;
        }else{
            [MBProgressHUD showError:@"相机不可用😭"];
            return;
        }
    }
    [self presentViewController:piker animated:YES completion:^{
    }];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    
    UIImage *img = info[UIImagePickerControllerEditedImage];
    [self uploadImage:img];
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void) uploadImage:(UIImage *) img {
    
    NSData *data = UIImageJPEGRepresentation(img, 0.5);
    NSString * imgStr = [data base64EncodedStringWithOptions:0];
    
    NSString *baseId = [LBUserManage defaultManager].userModel.ID;
    NSString *modularName = @"memberImg";
    NSString *busType = @"GRHHRSFZ";
    
    if (_currentBtn.tag == 101)
    {
        busType = @"GRHHRSFZ";
    }
    else if (_currentBtn.tag == 102)
    {
        busType = @"GRHHRSCSFZ";
    }
    UserModel *userModel = [LBUserManage defaultManager].userModel;
    NSMutableArray * array = @[].mutableCopy;
    for (UserModelImgList *list in userModel.ImgList) {
        if ([list.imgtype isEqualToString:busType]) {
            [array addObject:list.ID];
        }
    }
    NSString * delIds = @"";
    if (array.count > 0) {
        delIds = [array componentsJoinedByString:@","];
    }
    
    NSString *image = imgStr;
    
    [LBNetworkingInstance requestPOST:@"http://47.92.115.33:8181/FileUpService.asmx/uploadImage" parameters:NSDictionaryOfVariableBindings(baseId,modularName,busType,delIds,image) showHUD:YES headers:@{} progress:^(float progress) {
        
    } success:^(id  _Nonnull responseObject, NSInteger code, NSString * _Nonnull message) {
        
        [LBUserManage defaultManager].userModel = [UserModel yy_modelWithJSON:responseObject[@"Data"]];
        
        if (code == YCNetworkingStatusCodeSuccess)
        {
            if (_currentBtn.tag == 101)
            {
                _firstImage.image = img;
            }
            else if (_currentBtn.tag == 102)
            {
                _secondImage.image = img;
            }
        }
        
    } failure:^(NSError * _Nonnull err) {
        [MBProgressHUD showError:@"图片上传失败 请重试！"];
    }];
}

@end
